﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BbsbWebService.Service.Callback;
using System.ServiceModel;
using BbsbWebService.Service;
using System.ServiceModel.Web;

namespace BbsbWebService.Repositories
{
    internal static class ClientCommon
    {
        private static BbsbUpdateServiceClient _client;
        internal static void Initialise()
        {
            if (_client == null)
            {
                if (ApplicationState.IsConnectedToClient)
                {
                    EndpointAddress address = new EndpointAddress(ApplicationState.ServerMachine.ToBbsbUpdateAddress());
                    InstanceContext context = new InstanceContext(new BbsbUpdateCallback());
                    WSDualHttpBinding binding = new WSDualHttpBinding();
                    binding.Security = new WSDualHttpSecurity();
                    binding.Security.Mode = WSDualHttpSecurityMode.None;
                    _client = new BbsbUpdateServiceClient(context, binding, address);
                    _client.RegisterListener();
                }
            }
        }

        private static IBbsbService _service;

        internal static IBbsbService Service
        {
            get
            {
                if (_service == null)
                {
                    WebChannelFactory<IBbsbService> factory = new WebChannelFactory<IBbsbService>(new Uri(ApplicationState.ServerMachine.ToBbsbServiceAddress()));
                    _service = factory.CreateChannel();
                }

                return _service;
            }
        }
    }
}
